package com.auroramanito.uaa.security.filter;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.val;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;


@RequiredArgsConstructor
public class RestAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
    //通過构造函数将对象注入到Spring
    private final ObjectMapper objectMapper;

    /**
     *
     * {
     *     "username" :“张三”，
     *     “password":"123456"
     * }
     * */
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {

        UsernamePasswordAuthenticationToken authRequest;
        InputStream is = null;
        try {
            is = request.getInputStream();
            val jsonNode = objectMapper.readTree(is);
            String username = jsonNode.get("username").textValue();
            String password = jsonNode.get("password").textValue();
            authRequest = new UsernamePasswordAuthenticationToken(username,password);

        } catch (IOException e) {
            e.printStackTrace();
            throw new BadCredentialsException("没有找到用户名和密码");
        }


        setDetails(request,authRequest);
        return this.getAuthenticationManager().authenticate(authRequest);
    }
}
